<?php
namespace app\common\model;

class Members extends CommonModel
{
    //主键
    protected $pk = 'member_id';
	// 表名
    protected $name = 'members';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 时间字段自动转换
     */
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $type = [
        'create_time' => 'timestamp',
    ];

    // 追加属性
    protected $append = [];
    private $_limit = 20 ;
    // 用户状态
	const STATUS_ENABLE  = 1;
    const STATUS_FREZON  = 2;
	const STATUS_DISABLE = 3;
    public static $statusLabels = [
        self::STATUS_ENABLE  => '正常',
        self::STATUS_FREZON  => '已冻结',
        self::STATUS_DISABLE => '禁用',
    ];

    // 用户类型
    const TYPE_COMMON  = 1;
    const TYPE_SALESMAN  = 2;
    public static $typeLabels = [
        self::TYPE_COMMON  => '普通会员',
        self::TYPE_SALESMAN  => '业务员'
    ];
    const AGENT_ENABLE   = 1;
    const AGENT_DEFAULT  = 2;
    const AGENT_FROZEN   = 3;
    const AGENT_APPLICATION = 4 ;
    public static $AgentLabels = [
        self::AGENT_ENABLE  => '代理商',
        self::AGENT_DEFAULT  => '普通用户',
        self::AGENT_FROZEN => '冻结代理商',
        self::AGENT_APPLICATION  => '申请成为代理中',
    ];

    const AGENT_TYPE_ONE   = 1;
    const AGENT_TYPE_TWO  = 2;
    const AGENT_TYPE_THREE  = 3;
    const AGENT_TYPE_FOUR = 4 ;
    public static $AgentTypeLabels = [
        self::AGENT_TYPE_ONE  => '代理',
        self::AGENT_TYPE_TWO  => '币咚小咖',
        self::AGENT_TYPE_THREE => '币咚大咖',
        self::AGENT_TYPE_FOUR  => '币咚王者',
    ];

    // 用户状态
	const DEVICE_PC      = 1;
	const DEVICE_WAP     = 2;
	const DEVICE_ANDROID = 3;
	const DEVICE_IOS     = 4;
	const DEVICE_PANEL   = 5;
    public static $deviceLabels = [
		self::DEVICE_PC      => 'PC',
		self::DEVICE_WAP     => 'Wap',
		self::DEVICE_ANDROID => 'Android',
		self::DEVICE_IOS     => 'IOS',
		self::DEVICE_PANEL   => 'Panel',
    ];

    // 代理状态
    const AGENT_STATUS_YES    = 1;
    const AGENT_STATUS_CANCEL = 2;
    const AGENT_STATUS_NO     = 3;
    public static $agentLabels = [
        self::AGENT_STATUS_YES    => '正常',
        self::AGENT_STATUS_CANCEL => '取消',
        self::AGENT_STATUS_NO     => '冻结',
    ];

    public static $agentMembers = [];
    public static $teamMembers = [];
    public static $teamMemberIds = [];
    public static $agentNext = []; //间接代理统计

    /**
     * 获取用户信息
     */
    public function info($userId)
    {
        return self::getByMemberId($userId);
    }

    public function test($code)
    {
        $res = $this->fetchAll(['code' => $code]);

        foreach ($res as $key => $value) {  //全部下级
            $res[$key]['next'] = $this->test($value['member_id']);
        }
        return $res;
    }

    /**
     * Describe : 获取会员数量
     * Anthor :  xxxxxxx
     * Date   : 2018/10/2015:21
     * param  :
     * return :
     *
     */
    public function getMemberNumber($where){

        return $this->where($where)->count();
    }

    /**
     * Describe : 今日会员数量
     * Anthor :  xxxxxxx
     * Date   : 2018/10/2015:23
     * param  :
     * return :
     *
     */
    public function getTodayMember($where)
    {

        $time = strtotime(date('Ymd'));

        return  $this->where('create_time','>=',$time)->where($where)->count();

    }

    public function getAdminMember($userId)
    {
        if($userId == 1){
            return $this->field('member_id')->select()->toArray();
        }else{
            return $this->where(['manager_id'=>$userId])->field('member_id')->select()->toArray();
        }

    }

    /**
     * Describe : 会员列表
     * Anthor :  xxxxxxx
     * Date   : 2018/10/2215:23
     * param  :
     * return :
     *
     */
    public function getMembersList($where, $page, $orderby = 'm.create_time desc'){
        $list = $this->alias('m')
            ->join('member_account a','a.member_id = m.member_id')
            ->join('member_wallet mw','mw.member_id = m.member_id')
            ->where($where)
            ->field('m.member_id, m.code,m.phone,m.username,m.create_time,m.update_time,m.status, m.win_ratio, m.is_govern,,a.btc_amount,a.eth_amount,mw.usdt')
            ->order($orderby)
            ->limit($page * $this->_limit, $this->_limit)->select()->toArray();

        $total = $this->alias('m')->join('member_account a','a.member_id = m.member_id')
            ->join('member_wallet mw','mw.member_id = m.member_id')->where($where)->count();
        return ['list'=>$list,'total'=>$total];
    }

  /**
   * Describe : 会员列表
   * Anthor :  xxxxxxx
   * Date   : 2018/10/2215:23
   * param  :
   * return :
   *
   */
  public function getMembersLists($where){
    $list = $this->alias('m')
      ->join('MemberWallet w','m.member_id = w.member_id')
      ->where($where)
      ->field('m.*,w.usdt')
      ->order('m.create_time desc')
      ->select()->toArray();
    return $list;
  }

    /**
     * Describe : 后台用户详情
     * Anthor :  xxxxxxx
     * Date   : 2018/10/2215:55
     * param  :
     * return :
     *
     */
    public  function getMemberDetails($where){
        return $this->where($where)->field('member_id, link_id,code,phone,username,is_spread,is_agent,create_time,update_time,is_govern,win_ratio,status')->find();
    }

    /**
     * 获取业务员列表
     */
    public function getSellerList($filter, $page, $limit, $order = 'create_time desc')
    {
        $res   = $this->field('member_id,manager_id,username,phone,code,status,extract_rate,create_time')->where($filter)->order($order)->limit($page, $limit)->select();
        $res   = $res ? $res->toArray() : [];
        $extractModel = model('common/Extract');
        $recommendModel = model('common/Recommend');
        //推广人数统计/提成统计
        foreach ($res as &$value) {
            $extractTotal = $extractModel->sumData(['member_id' => $value['member_id'], 'status' => $extractModel::STATUS_SOLVE], 'extract');
            $recommendTotal = $recommendModel->countData(['member_id' => $value['member_id']], 'recommend_id');
            $value['extract_total'] = $extractTotal;
            $value['recommend_total'] = $recommendTotal;
        }

        $total = $this->where($filter)->count();
        return ['list' => $res, 'total' => $total];
    }

    public function  memberInfo($userId)
    {
        return $this->where(['member_id' =>$userId])->find();
    }

    /**
     * 获取管理员下面的业务员列表
     */
    public function adminUserSeller($filter, $page, $limit)
    {
        $res = $this->field('member_id,manager_id,username,phone,code,status,extract_rate,create_time,type,profit,stream')->where($filter)->limit($page, $limit)->select();
        $res   = $res ? $res->toArray() : [];
        $extractModel = model('common/Extract');
        $recommendModel = model('common/Recommend');
        //推广人数统计/提成统计
        foreach ($res as &$value) {
            $recommendTotal = $recommendModel->countData(['member_id' => $value['member_id']], 'recommend_id');
            $value['recommend_total'] = $recommendTotal;
        }

        $total = $this->where($filter)->count();
        return ['list' => $res, 'total' => $total];
    }


    /**
     * Describe : 推荐用户
     * Anthor :
     * Date   : 2018/11/214:49
     * param  :
     * return :
     *
     */
    public  function getRecommendPeople($recommendId)
    {
        return $this->where('member_id','in',$recommendId)->field('member_id,username,phone')->select()->toArray();
    }

    /**
     * Describe : 用户详情
     * Anthor :
     * Date   : 2018/11/214:49
     * param  :
     * return :
     *
     */
    public function  getMemberInfo($where)
    {
        return $this->where($where)->select()->toArray();
    }


    public function  resetData($userId, $type,$filed,$amount)
    {
        if($type ==1){
            return $this->where(['member_id'=>$userId])->setInc($filed,$amount);
        }else{
            return $this->where(['member_id'=>$userId])->setDec($filed,$amount);
        }
    }

    public function  updateUser($where,$data)
    {
        return $this->where($where)->update($data);
    }

    /**
     * 获取代理列表
     */
    public function statAgnetProfit($memberId)
    {
        $recommendModel = model('common/Recommend');
        $res = $recommendModel->fetchAll(['member_id' => $memberId]);
        foreach ($res as $value) {
            $memberInfo = $this->fetch(['member_id' => $value['referee_id']], 'member_id,avatar,username,phone,profit,agent_status,create_time');
            if(isset($memberInfo['agent_status'])){
                self::$agentMembers[] = $memberInfo;
            }
            $allInfo = $this->statAgnetProfit($value['referee_id']);
            // $res['next'] = $allInfo;
        }
        return $res;
    }

    /**
     * 统计直接代理的下级
     */
    public function statForAgent($memberId)
    {
        $recommendModel = model('common/Recommend');
        $res = $recommendModel->fetchAll(['member_id' => $memberId]);
        foreach ($res as $value) {
            $memberInfo = $this->fetch(['member_id' => $value['referee_id']], 'member_id,avatar,username,phone,profit,agent_status,create_time');
            if(isset($memberInfo['agent_status']) && $memberInfo['agent_status'] == self::AGENT_STATUS_YES){
                continue;
            }
            self::$agentNext[] = $memberInfo['member_id'];
            $allInfo = $this->statAgnetProfit($value['referee_id']);
            // $res['next'] = $allInfo;
        }
        return $res;
    }



    public function statAgentProfit($memberId)
    {
        $recommendModel = model('common/Recommend');
        $res = $recommendModel->fetchAll(['member_id' => $memberId]);
        foreach ($res as $value) {
            $memberInfo = $this->fetch(['member_id' => $value['referee_id']], 'member_id,avatar,username,phone,profit,agent_status,create_time');
            if(isset($memberInfo['agent_status']) && $memberInfo['agent_status'] == self::AGENT_STATUS_YES){
                self::$agentMembers[] = $memberInfo;
            }
            $allInfo = $this->statAgnetProfit($value['referee_id']);
           // $res['next'] = $allInfo;
        }
        return $res;
    }
    /**
     * 团队收益
     */
    public function statTeamProfit($memberId)
    {
        $recommendModel = model('common/Recommend');
        $res = $recommendModel->fetchAll(['member_id' => $memberId]);
        foreach ($res as $value) {
            $memberInfo = $this->fetch(['member_id' => $value['referee_id']], 'member_id,avatar,username,phone,profit,agent_status,create_time');
            if(isset($memberInfo['agent_status']) && $memberInfo['agent_status'] == self::AGENT_STATUS_CANCEL){
                self::$teamMembers[] = $memberInfo;
                self::$teamMemberIds[] = $memberInfo['member_id'];
                $allInfo = $this->statTeamProfit($value['referee_id']);
            }
            // $res['next'] = $allInfo;
        }
        return $res;
    }
    public function userPhone($where)
    {
        return $this->where($where)->field('member_id,phone')->select()->toArray();
    }

    /**
     * 运营下代理数量
     * @return int
     */
    public function getUserOperateNumber($where)
    {
        return $this->where($where)->group('manager_id')->field('manager_id,count(*) as count')->select()->toArray();
    }

    /*
     * 获取运营下的代理
     */
    public  function  getOperateUserAgent($where){
        return $this->where($where)->field('manager_id,agent_manager_id,member_id,username,phone,code,extract_rate,agent_status,create_time')->select()->toArray();
    }

    /*
     * 代理商下用户数量
     */
    public function getUserAgentNumber($where)
    {
        return $this->where($where)->group('agent_manager_id')->field('agent_manager_id,count(*) as count')->select()->toArray();
    }

    public  function  getExtensionMember(){

    }
}